<template>
  <div class="app-container">
    <el-form :model="defaultKnowledge" disabled>
      <el-row :gutter="10" class="mb8">
        <el-col :span="6">
          <el-form-item label="知识库名称">
            {{ defaultKnowledge.name }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="描述">
            {{ defaultKnowledge.description }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="向量维度">
            {{ defaultKnowledge.dimensions }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="稀疏向量">
            <dict-tag :options="knowledgeEnableSparseOptions" :value="defaultKnowledge.enable_sparse" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名" prop="file_name">
        <el-input
          v-model="queryParams.file_name"
          placeholder="请输入文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="数据状态" clearable>
          <el-option
            v-for="dict in knowledgeDocumentStatusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleToAdd"
          :disabled="parentLoading"
        >上传文件</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-grape"
          size="mini"
          :disabled="multiple"
          @click="handleProcessing"
        >向量化</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-tickets"
          size="mini"
          :disabled="multiple"
          @click="handleChangeStatusToDraft"
        >变更为草稿</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-close"-->
<!--          size="mini"-->
<!--          @click="handleClose"-->
<!--        >关闭</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="文件名" align="center" prop="file_name" />
      <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="文件大小" align="center" prop="file_size" :show-overflow-tooltip="true" :formatter="formatterFileSize"/>
      <el-table-column label="文件类型" align="center" prop="content_type" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="knowledgeDocumentStatusOptions" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="状态时间" align="center" prop="status_time" width="180" :formatter="formatterTimeYmdHm"/>
      <el-table-column label="创建时间" align="center" prop="created_at" width="180" :formatter="formatterTimeYmdHm"/>
      <el-table-column label="更新时间" align="center" prop="updated_at" width="180" :formatter="formatterTimeYmdHm"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleChangeDocumentStatusDialog(scope.row)"
          ><svg-icon icon-class="edit" />变更状态</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="知识库ID" prop="knowledge_base_id">
          <el-input v-model="form.knowledge_base_id" :disabled="true" />
        </el-form-item>
        <el-form-item label="文件名" prop="file_name" >
          <el-input v-model="form.file_name" placeholder="请输入文件名" :disabled="true" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="文件大小" prop="file_size">
          <el-input v-model="form.file_size" type="number" placeholder="请输入文件大小" :disabled="true" />
        </el-form-item>
        <el-form-item label="文件类型" prop="content_type">
          <el-input v-model="form.content_type" placeholder="请输入文件类型" :disabled="true" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status" :disabled="true" >
            <el-radio
              v-for="dict in knowledgeDocumentStatusOptions"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="错误信息" prop="error_message">
          <el-input v-model="form.error_message" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <KnowledgeDocAddDialog ref="knowledgeDocAddDialogRef" />
    <MsgInfoByDelDocDialog ref="msgInfoByDelDocDialogRef"/>
    <MsgInfoByDelDocDialog ref="msgInfoByDelDocDialogRef"/>
    <MsgInfoByProcessDocDialog ref="msgInfoByProcessDocRef"/>
    <MsgInfoByKnowledgeDocChangeStatusToDraftDialog ref="msgInfoByKnowledgeDocChangeStatusToDraftDialogRef"/>
    <KnowledgeDocChangeStatusDialog ref="knowledgeDocChangeStatusDialogRef"/>
  </div>
</template>

<script>
import {
  changeDocumentStatus, changeDocumentStatusToDraft,
  delDocument,
  getDocument,
  getKnowledge,
  listDocument,
  processingDocument,
  updateDocument
} from '@/api/knowledge'
import { knowledgeDocumentStatusOptions, knowledgeEnableSparseOptions } from '@/utils/dicts'
import { Loading, Message } from 'element-ui'
import KnowledgeDocAddDialog from '@/views/knowledge/kb-doc-add-dialog.vue'
import MsgInfoByDelDocDialog from '@/views/knowledge/msg-info-by-del-doc-dialog.vue'
import MsgInfoByProcessDocDialog from '@/views/knowledge/msg-info-by-process-doc-dialog.vue'
import KnowledgeDocChangeStatusDialog from '@/views/knowledge/knowledge-doc-change-status-dialog.vue'
import MsgInfoByKnowledgeDocChangeStatusToDraftDialog
  from '@/views/knowledge/msg-info-by-knowledge-doc-change-status-to-draft-dialog.vue'

export default {
  name: "KnowledgeDoc",
  components: { KnowledgeDocAddDialog,MsgInfoByDelDocDialog ,MsgInfoByProcessDocDialog,KnowledgeDocChangeStatusDialog,MsgInfoByKnowledgeDocChangeStatusToDraftDialog},
  data() {
    return {
      parentLoading: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      knowledgeDocumentStatusOptions: knowledgeDocumentStatusOptions,
      knowledgeEnableSparseOptions: knowledgeEnableSparseOptions,
      // 字典表格数据
      dataList: [],
      defaultKb_id: undefined,
      // 默认字典类型
      defaultKnowledge: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 数据标签回显样式
      listClassOptions: [
        {
          value: "default",
          label: "默认"
        },
        {
          value: "primary",
          label: "主要"
        },
        {
          value: "success",
          label: "成功"
        },
        {
          value: "info",
          label: "信息"
        },
        {
          value: "warning",
          label: "警告"
        },
        {
          value: "danger",
          label: "危险"
        }
      ],
      // 查询参数
      queryParams: {
        kb_id: undefined,
        pageNum: 1,
        pageSize: 10,
        status: undefined,
        file_name: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        file_name: [
          { required: true, message: "文件名不能为空", trigger: "blur" }
        ],
        description: [
          { required: true, message: "描述不能为空", trigger: "blur" }
        ],
        file_size: [
          { required: true, message: "文件大小不能为空", trigger: "blur" }
        ],
        content_type: [
          { required: true, message: "文件类型不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    const defaultKb_id = this.$route.params && this.$route.params.kbId;
    this.defaultKb_id = defaultKb_id;
    this.getKnowledge(defaultKb_id);
  },
  methods: {
    /** 查询字典类型详细 */
    getKnowledge(kbId) {
      let loading = Loading.service({
        lock: true,
        text: "拼命处理中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      getKnowledge(kbId).then(response => {
        this.defaultKnowledge = response.data;
        this.getList();
        loading?.close();
        this.parentLoading = false;
      });
    },
    /** 查询字典数据列表 */
    getList() {
      this.loading = true;
      const queryParams = this.queryParams;
      queryParams.kb_id = this.defaultKb_id;
      listDocument(queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        knowledge_base_id: undefined,
        file_name: undefined,
        description: undefined,
        file_size: undefined,
        content_type: undefined,
        status: "draft",
        error_message: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 返回按钮操作 */
    handleClose() {
      const obj = { path: "/system/dict" };
      this.$tab.closeOpenPage(obj);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.dictType = this.defaultKnowledge;
      this.handleQuery();
    },
    handleToAdd({ data, title = '新增知识库文件' } = {}) {
      this.$refs.knowledgeDocAddDialogRef.show({
        form: this.sksUtils.mergeFromObject({}, data, {
          kb_id: this.defaultKnowledge.id,
          payMode: 1,
          virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.add,
        }),
        dialogInfo: {
          width: '90%',
          title: title,
          submitCallbackSuccess: ({ resData } = {}) => {
          },
          closeCallback:()=>{
            this.getList()
          }
        }
      })
    },

    handleChangeDocumentStatusDialog(row){
      let title='知识库文件变更状态'
      this.$refs.knowledgeDocChangeStatusDialogRef.show({
        form: this.sksUtils.mergeFromObject({}, row, {
          virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.modify,
        }),
        dialogInfo: {
          width: '200',
          title: title,
          submitCallbackSuccess: ({ resData } = {}) => {
            // this.sksUtils.msgSuccess(`新增后回调` + JSON.stringify(resData, null))
            this.getList()
          },
          closeCallback:()=>{
            // this.getList()
          }
        }
      })

    },
    msgInfoByChangeDocumentStatusToDraftDialog({data}={}){
      let title='知识库文件状态变更为草稿提示'
      this.$refs.msgInfoByKnowledgeDocChangeStatusToDraftDialogRef.show({
        form: this.sksUtils.mergeFromObject({}, data, {
          // virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.add,
        }),
        dialogInfo: {
          width: '90%',
          title: title,
          submitCallbackSuccess: ({ resData } = {}) => {
            // this.sksUtils.msgSuccess(`新增后回调` + JSON.stringify(resData, null))
          },
          closeCallback:()=>{
            // this.getList()
          }
        }
      })

    },
    msgInfoByProcessDocDialog({data}={}){
      let title='知识库文件向量化结果提示'
      this.$refs.msgInfoByProcessDocRef.show({
        form: this.sksUtils.mergeFromObject({}, data, {
          // virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.add,
        }),
        dialogInfo: {
          width: '90%',
          title: title,
          submitCallbackSuccess: ({ resData } = {}) => {
            // this.sksUtils.msgSuccess(`新增后回调` + JSON.stringify(resData, null))
          },
          closeCallback:()=>{
            // this.getList()
          }
        }
      })
    },
    msgInfoByDelDocDialog({data}={}){
      let title='知识库文件删除结果提示'
      this.$refs.msgInfoByDelDocDialogRef.show({
        form: this.sksUtils.mergeFromObject({}, data, {
          // virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.add,
        }),
        dialogInfo: {
          width: '90%',
          title: title,
          submitCallbackSuccess: ({ resData } = {}) => {
            // this.sksUtils.msgSuccess(`新增后回调` + JSON.stringify(resData, null))
          },
          closeCallback:()=>{
            // this.getList()
          }
        }
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDocument(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文件信息";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateDocument(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleProcessing(row){
      const ids = row.id?[row.id]:this.ids;
      this.$modal.confirm('是否确认向量化ID为"' + ids + '"的数据项？').then(()=> {
        return processingDocument(ids);
      }).then((response) => {
        console.log("handleProcessing",response)
        this.getList();
        this.msgInfoByProcessDocDialog({data:response.data})
      }).catch((error) => {
        console.error(error)
      });
    },
    handleChangeStatusToDraft(){
      const ids=this.ids
      const data = {
        ids: ids
      };
      this.$modal.confirm('是否确认将ID为"' + ids + '"的数据项都变更为草稿？').then(()=> {
        return changeDocumentStatusToDraft(data);
      }).then((response) => {
        console.log("handleChangeStatusToDraft",response)
        this.getList();
        this.msgInfoByChangeDocumentStatusToDraftDialog({data:response.data})
      }).catch((error) => {
        console.error(error)
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id?[row.id]:this.ids;
      this.$modal.confirm('是否确认删除ID为"' + ids + '"的数据项？').then(()=> {
        return delDocument(ids);
      }).then((response) => {
        console.log("handleDelete",response)
        this.getList();
        this.msgInfoByDelDocDialog({data:response.data})
        // let {msg,hasError}= this.formatResultMessage(response)
        // console.log("msg",msg)
        // Message({ duration:600000,
        //   dangerouslyUseHTMLString: true,
        //   showClose: true,
        //   message: msg,
        //   type: hasError?"error":"success" })
      }).catch((error) => {
        console.error(error)
      });
    },
    formatResultMessage(response){
      let msg=""
      let hasError=false
      if(!this.sksUtils.arrayIsEmpty(response.data.errorMsg)){
        msg=`删除失败${response.data.errorMsg.length}项,原因如下<br/>`
        msg+=response.data.errorMsg.join("<br/>")
        msg+="<br><br>"
        hasError=true
      }
      if(!this.sksUtils.arrayIsEmpty(response.data.successMsg)){
        msg+=`删除成功${response.data.successMsg.length}项,详细信息如下<br/>`
        msg+=response.data.successMsg.join("<br/>")
      }
      return {msg,hasError}
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/dict/data/export', {
        ...this.queryParams
      }, `data_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
